package telnet

import (
	"fmt"
	"net"
	"oonadare/console"
)

const (
	port = 5335
)

type TelnetServer struct {
	sessions map[int64]*Session
	control  chan string
}

func (ts *TelnetServer) Run() {
	go ts.serve()
	for {
		select {
		case <-ts.control:
			return
		}
	}
}

func (ts *TelnetServer) serve() {
	service := fmt.Sprintf(":%d", port)
	tcpAddr, err := net.ResolveTCPAddr("tcp", service)
	if err != nil {
		fmt.Println(err.Error())
	}
	listener, err := net.ListenTCP("tcp4", tcpAddr)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println("listening on: " + tcpAddr.IP.String() + service)
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		go ts.handleClient(conn)
	}
}

func (ts *TelnetServer) handleClient(conn net.Conn) {
	session := console.OpenSession(conn, conn)
	session.Run()
}

type Session struct{}

var Server = &TelnetServer{make(map[int64]*Session), make(chan string, 1)}
